package com.huanuo.internetofthings.controller.fastStatistics;

import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.unicorn.framework.core.ResponseDto;
import org.unicorn.framework.core.SysCode;
import org.unicorn.framework.core.exception.PendingException;

import com.huanuo.internetofthings.bo.fastStatistics.FastStatistics;
import com.huanuo.internetofthings.bo.user.UserInfo;
import com.huanuo.internetofthings.service.fastStatistics.FastStatisticsService;
import com.huanuo.internetofthings.service.user.UserInfoService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * fast数据统计表 前端控制器
 * </p>
 *
 * @author xiebin
 * @since 2018-07-20
 */
@RestController
@RequestMapping("/fastStatistics")
@Api(value = "FAST统计模块", tags = { "FAST统计模块" })
public class FastStatisticsController {
	@Autowired
	private FastStatisticsService fastStatisticsService;
	@Autowired
	private UserInfoService userInfoService;

	/**
	 * Fast详情
	 * 
	 * @return
	 * @throws PendingException
	 */
	@ApiOperation("Fast详情")
	@RequestMapping(value = { "/info" }, method = { RequestMethod.POST })
	public ResponseDto<?> queryInfo(@RequestBody FastStatistics fastStatistics) throws PendingException {
		// 获得用户信息
		String userIdentity = (String) SecurityUtils.getSubject().getPrincipal();
		if (StringUtils.isBlank(userIdentity)) {
			throw new PendingException(SysCode.SESSION_ERROR);
		}
		UserInfo userInfo = checkUser(userIdentity);
		fastStatistics.setGroupNo(userInfo.getGroupNo());
		Calendar c=Calendar.getInstance();
		fastStatistics.setYear(c.get(Calendar.YEAR));
		fastStatistics.setMonth(c.get(Calendar.MONTH)+1);
		if(fastStatistics.getPRegionId()==null){
			fastStatistics.setPRegionId(0);
		}
		return fastStatisticsService.queryInfo(fastStatistics);
	}

	/**
	 * 检查用户
	 * 
	 * @param userIdentity
	 * @return
	 * @throws PendingException
	 */
	public UserInfo checkUser(String userIdentity) throws PendingException {
		// 根据用户标识查询用户信息
		UserInfo userInfo = userInfoService
				.getUserInfoByCondition(UserInfo.builder().userIdentity(userIdentity).build());
		if (userInfo == null) {
			throw new PendingException(SysCode.SESSION_ERROR);
		}
		if (StringUtils.isBlank(userInfo.getGroupNo())) {
			throw new PendingException(SysCode.SYS_FAIL, "用户不属于任何组");
		}
		return userInfo;
	}
}
